package com.dengyafei.service.impl;

import com.dengyafei.annotation.JwtToken;
import com.dengyafei.bean.GraduateEntity;
import com.dengyafei.constant.RecommendConstant;
import com.dengyafei.constant.RedisKeyConstant;
import com.dengyafei.domin.dto.*;
import com.dengyafei.domin.vo.*;
import com.dengyafei.exception.RedisListUpdateException;
import com.dengyafei.helper.BeanHelper;
import com.dengyafei.mapper.GraduateEntityMapper;
import com.dengyafei.mapper.ResumeEntityMapper;
import com.dengyafei.result.RedisLoginEntity;
import com.dengyafei.result.ResumeInfoEntity;
import com.dengyafei.service.GraduateService;
import com.dengyafei.service.ResumeService;
import com.dengyafei.utils.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.Base64Utils;
import org.springframework.util.ObjectUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.text.ParseException;
import java.util.Date;
import java.util.List;


/**
 * @author 邓亚非
 */
@Slf4j
@Service
public class GraduateServiceImpl implements GraduateService {
    @Autowired
    RedisTemplate<Object, Object> redisTemplate;
    @Autowired
    GraduateEntityMapper graduateEntityMapper;
    @Autowired
    ResumeService resumeService;
    @Autowired
    HttpServletRequest request;
    @Autowired
    StringRedisTemplate stringRedisTemplate;

    /**
     * 应届生注册service
     *
     * @param graduateRegisterVO
     * @return
     */
    @Override
    public Integer graduateRegister(GraduateRegisterVO graduateRegisterVO) {
        GraduateRegisterDTO graduateRegisterDTO = BeanHelper.copyProperties(graduateRegisterVO, GraduateRegisterDTO.class);
//        验证有没有被注册过
        GraduateEntity graduateEntity = graduateEntityMapper.queryAllByGname(graduateRegisterVO.getGname());
        if (!ObjectUtils.isEmpty(graduateEntity)) {
            return RecommendConstant.ALREADY_REGISTER;
        }
//        没有被注册过存入缓存
        Integer integer = graduateEntityMapper.graduateRegister(graduateRegisterDTO);
        if (!integer.equals(RecommendConstant.OPERATION_SUCCESS)) {
            return RecommendConstant.REGISTER_FAILURE;
        }
//        注册成功写入缓存
        RedisLoginEntity redisLoginEntity = new RedisLoginEntity();
        redisLoginEntity.setUsername(graduateRegisterVO.getGname());
        redisLoginEntity.setPassword(graduateRegisterVO.getGpassword());
        Long graduateLogin = redisTemplate.opsForList().leftPush("graduateLogin", redisLoginEntity);
        return integer;
    }

    /**
     * 应届生登录接口
     *
     * @return
     */
    @Override
    public Integer graduateLogin(GraduateLoginVO graduateLoginVO) {
//        查缓存
        RedisLoginEntity redisLoginEntity = BeanHelper.copyProperties(graduateLoginVO, RedisLoginEntity.class);
        Integer login = RedisListUtil.getLogin(redisTemplate, RedisKeyConstant.GraduateRedis.GRADUATE_LOGIN, redisLoginEntity);
        GraduateEntity graduateEntity = null;
//        如果redis查询结果为null,就查数据库
        if (login.equals(RecommendConstant.REDIS_NULL)) {
            graduateEntity = graduateEntityMapper.queryAllByGname(graduateLoginVO.getUsername());
        } else {
//            如果不为空返回redis查询结果;不走mysql
            return login;
        }
//        mysql层判断
        Integer integer = LoginSqlUtil.queryGraduateLoginBySql(graduateEntity, graduateLoginVO);
        return integer;
    }

    /**
     * 应届生找回密码
     *
     * @param resetPasswordVO
     * @return
     */
    @Override
    public Integer graduateFindPassword(ResetPasswordVO resetPasswordVO) {
        ResetPasswordDTO resetPasswordDTO = BeanHelper.copyProperties(resetPasswordVO, ResetPasswordDTO.class);
        Integer integer = graduateEntityMapper.resetPassword(resetPasswordDTO);
        if (!integer.equals(RecommendConstant.OPERATION_SUCCESS)) {
            return RecommendConstant.RESET_FAILURE;
        }
//        重置成功修改缓存
        RedisLoginEntity redisLoginEntity = BeanHelper.copyProperties(resetPasswordDTO, RedisLoginEntity.class);
        boolean listIndex = RedisListUtil.updateRedisList(redisTemplate, RedisKeyConstant.GraduateRedis.GRADUATE_LOGIN, redisLoginEntity);
        if (!listIndex) {
            throw new RedisListUpdateException();
        }
        return integer;
    }

    /**
     * 应届生重置密码
     *
     * @param resetPasswordVO
     * @return
     */
    @Override
    public Integer graduateUpdatePassword(ResetPasswordVO resetPasswordVO) {
        return null;
    }

    /**
     * 查询应届生信息
     *
     * @param graduateUpdatePasswordVO
     * @return
     */
    @Override
    public GraduateEntity queryByName(GraduateUpdatePasswordVO graduateUpdatePasswordVO) {
        return graduateEntityMapper.queryAllByGname(graduateUpdatePasswordVO.getName());
    }

    /**
     * 获取个人信息
     *
     * @return
     */
    @Override
    public GraduateIntroductionDTO queryMyIntroduction() {
//        取出token
        String realToken = JwtUtil.getRealToken(request);
        String userInfo = JwtUtil.getUserInfo(realToken);
        GraduateEntity graduateEntity = graduateEntityMapper.queryAllByGname(userInfo);
        ResumeInfoEntity resumeInfoEntity = resumeService.computedScore(graduateEntity.getGid());
        GraduateIntroductionDTO graduateIntroductionDTO = BeanHelper.copyProperties(graduateEntity, GraduateIntroductionDTO.class);
//        类型转换
        String date = DateUtil.dateToString(graduateEntity.getGbirthday());
        String age = String.valueOf(graduateEntity.getGage());
//        set值
        graduateIntroductionDTO.setGbirthday(date);
        graduateIntroductionDTO.setGage(age);
        graduateIntroductionDTO.setScore(resumeInfoEntity.getScore());
        graduateIntroductionDTO.setIdentify(resumeInfoEntity.getIdentify());
        graduateIntroductionDTO.setCity(resumeInfoEntity.getCity());
        graduateIntroductionDTO.setEducation(resumeInfoEntity.getEducation());
        return graduateIntroductionDTO;
    }

    /**
     * 查询应届生信息
     *
     * @return
     */
    @Override
    public GraduateInfoDTO queryByGid() {
        String realToken = JwtUtil.getRealToken(request);
        String userInfo = JwtUtil.getUserInfo(realToken);
        GraduateEntity graduateEntity = graduateEntityMapper.queryAllByGname(userInfo);
        String string = DateUtil.dateToString(graduateEntity.getGbirthday());
        GraduateInfoDTO graduateInfoDTO = new GraduateInfoDTO();
        graduateInfoDTO.setGid(graduateEntity.getGid());
        graduateInfoDTO.setGname(graduateEntity.getGname());
        graduateInfoDTO.setGnickname(graduateEntity.getGnickname());
        graduateInfoDTO.setGpassword(graduateEntity.getGpassword());
        graduateInfoDTO.setGschoolname(graduateEntity.getGschoolname());
        graduateInfoDTO.setGbirthday(string);
        graduateInfoDTO.setGage(graduateEntity.getGage());
        graduateInfoDTO.setGsex(graduateEntity.getGsex());
        graduateInfoDTO.setGphone(graduateEntity.getGphone());
        graduateInfoDTO.setEmail(graduateEntity.getEmail());
        return graduateInfoDTO;
    }

    /**
     * 更新应届生信息
     *
     * @param graduateUpdateVO
     * @return
     */
    @Override
    public Integer updateGraduateInfo(GraduateUpdateVO graduateUpdateVO) throws ParseException {
        Date date = DateUtil.stringToDate(graduateUpdateVO.getGbirthday());
        GraduateEntity graduateEntity = new GraduateEntity();
        graduateEntity.setGid(graduateUpdateVO.getGid());
        graduateEntity.setGname(graduateUpdateVO.getGname());
        graduateEntity.setGage(graduateUpdateVO.getGage());
        graduateEntity.setGsex(graduateUpdateVO.getGsex());
        graduateEntity.setGbirthday(date);
        graduateEntity.setGpassword(graduateUpdateVO.getGpassword());
        graduateEntity.setEmail(graduateUpdateVO.getEmail());
        graduateEntity.setGphone(graduateUpdateVO.getGphone());
        graduateEntity.setGnickname(graduateUpdateVO.getGnickname());
        graduateEntity.setGschoolname(graduateUpdateVO.getGschoolname());
        return graduateEntityMapper.updateByPrimaryKey(graduateEntity);
    }

    /**
     * 应届生修改密码
     *
     * @param graduateUpdatePasswordVO
     * @return
     */
    @Override
    public Integer updateGraduatePassword(GraduateUpdatePasswordVO graduateUpdatePasswordVO) {
        GraduateUpdatePasswordDTO graduateUpdatePasswordDTO = BeanHelper.copyProperties(graduateUpdatePasswordVO, GraduateUpdatePasswordDTO.class);
        Integer integer = graduateEntityMapper.updatePassword(graduateUpdatePasswordDTO);
        if (!integer.equals(RecommendConstant.OPERATION_SUCCESS)) {
            return integer;
        }
//        修改redis中的密码
        List<Object> range = redisTemplate.opsForList().range(RedisKeyConstant.GraduateRedis.GRADUATE_LOGIN, 0, -1);
        List<RedisLoginEntity> redisLoginEntities = BeanHelper.copyWithCollection(range, RedisLoginEntity.class);
        RedisLoginEntity redisLoginEntity = null;
        long index = 0;
        for (int i = 0; i < redisLoginEntities.size(); i++) {
            if (graduateUpdatePasswordVO.getName().equals(redisLoginEntities.get(i).getUsername())) {
                index = i;
                redisLoginEntity = redisLoginEntities.get(i);
            }
        }
        redisLoginEntity.setPassword(graduateUpdatePasswordVO.getNewPassword());
        redisTemplate.opsForList().set(RedisKeyConstant.GraduateRedis.GRADUATE_LOGIN, index, redisLoginEntity);
        return integer;
    }

    /**
     * 用户保存头像到redis缓存中
     * @param graduateHeadImageVO
     * @return
     */
    @Override
    public Boolean saveHeadImage(GraduateHeadImageVO graduateHeadImageVO) throws IOException {
        String realToken = JwtUtil.getRealToken(request);
        System.out.println(realToken);
        String userInfo = JwtUtil.getUserInfo(realToken);
        GraduateEntity graduateEntity = graduateEntityMapper.queryAllByGname(userInfo);
        String headImageKey=RedisKeyConstant.HeadImageRedis.GRADUATE_HEAD_IMAGE_PREFIX+graduateEntity.getGid();
        try {
            stringRedisTemplate.opsForValue().set(headImageKey,graduateHeadImageVO.getImgUrl());
            return true;
        } catch (Exception e) {
           log.info("更新成功");
        }
        return false;
    }

    /**
     * 查询imageurl
     * @return
     */
    @Override
    public String queryImageUrl() {
        String realToken = JwtUtil.getRealToken(request);
        String userInfo = JwtUtil.getUserInfo(realToken);
        GraduateEntity graduateEntity = graduateEntityMapper.queryAllByGname(userInfo);
        String key=RedisKeyConstant.HeadImageRedis.GRADUATE_HEAD_IMAGE_PREFIX+graduateEntity.getGid();
        String s = stringRedisTemplate.opsForValue().get(key);
        return s;
    }

    /**
     * 查询所有毕业生
     * @return
     */
    @Override
    public List<GraduateEntity> queryGraduates() {
        return graduateEntityMapper.queryGraduates();
    }
}